package com.beordie.controller;

import com.beordie.model.Bill;
import com.beordie.model.Type;
import com.beordie.service.BillService;
import com.beordie.service.TypeService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @Description 账单控制器
 * @Date 2021/8/3 8:35
 * @Created 30500
 */
@Controller
@RequestMapping("bill")
public class BillController {
    @Autowired
    private TypeService typeService;

    @Autowired
    private BillService billService;


    @RequestMapping("index")
    public String test() {
        return "index";
    }

    @RequestMapping("list")
    public String pageList(@RequestParam(defaultValue = "1") int pageNum,
                           @RequestParam(defaultValue = "10") int pageSize,
                           Bill bill, Model model) {
        List<Type> typeList = typeService.getAll();
        model.addAttribute("types", typeList);

        PageInfo<Bill> billPageInfo = billService.billPageInfo(pageNum, pageSize, bill);
        model.addAttribute("pageInfo", billPageInfo);
        return "bill/list";
    }

    @RequestMapping(value = "toAdd", method = RequestMethod.GET)
    public String toAdd(Model model) {
        List<Type> typeList = typeService.getAll();
        model.addAttribute("types", typeList);
        return "bill/add";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String add(Bill bill) {
        bill.setTime(new Date());
        int add = billService.add(bill);
        return "redirect:/bill/list";
    }

    @RequestMapping(value = "toUpdate/{id}", method = RequestMethod.GET)
    public String toUpdate(@PathVariable("id") int id, Model model) {
        Bill bill = billService.selectById(id);
        List<Type> typeList = typeService.getAll();
        model.addAttribute("types", typeList);
        model.addAttribute("bill", bill);
        return "bill/update";
    }

    @RequestMapping("delete/{id}")
    public String delete(@PathVariable("id") int id) {
        int delete = billService.delete(id);
        return "redirect:/bill/list";
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(Bill bill) {
        int update = billService.update(bill);
        return "redirect:/bill/list";
    }
}
